<template>
  <div class="change-password">
    <div class="page-header">
      <h1>修改密码</h1>
      <div class="breadcrumb">系统管理 / 修改密码</div>
    </div>

    <div class="password-content">
      <!-- 密码修改卡片 -->
      <div class="password-card">
        <div class="card-header">
          <div class="header-icon">🔒</div>
          <div class="header-text">
            <h2>修改登录密码</h2>
            <p>为了账户安全，请定期更换密码</p>
          </div>
        </div>

        <div class="password-form">
          <div class="form-group">
            <label for="currentPassword">
              <span class="label-text">当前密码</span>
              <span class="required">*</span>
            </label>
            <div class="input-wrapper">
              <input 
                id="currentPassword"
                v-model="passwordForm.currentPassword" 
                :type="showCurrentPassword ? 'text' : 'password'"
                placeholder="请输入当前密码"
                class="form-input"
                :class="{ 'error': errors.currentPassword }"
                @input="clearError('currentPassword')"
              />
              <button 
                type="button" 
                class="password-toggle"
                @click="showCurrentPassword = !showCurrentPassword"
              >
                {{ showCurrentPassword ? '👁️' : '🙈' }}
              </button>
            </div>
            <div v-if="errors.currentPassword" class="error-message">
              {{ errors.currentPassword }}
            </div>
          </div>

          <div class="form-group">
            <label for="newPassword">
              <span class="label-text">新密码</span>
              <span class="required">*</span>
            </label>
            <div class="input-wrapper">
              <input 
                id="newPassword"
                v-model="passwordForm.newPassword" 
                :type="showNewPassword ? 'text' : 'password'"
                placeholder="请输入新密码"
                class="form-input"
                :class="{ 'error': errors.newPassword }"
                @input="validateNewPassword"
              />
              <button 
                type="button" 
                class="password-toggle"
                @click="showNewPassword = !showNewPassword"
              >
                {{ showNewPassword ? '👁️' : '🙈' }}
              </button>
            </div>
            <div class="password-strength">
              <div class="strength-bar">
                <div 
                  class="strength-fill" 
                  :class="passwordStrength.class"
                  :style="{ width: passwordStrength.percentage + '%' }"
                ></div>
              </div>
              <span class="strength-text" :class="passwordStrength.class">
                {{ passwordStrength.text }}
              </span>
            </div>
            <div v-if="errors.newPassword" class="error-message">
              {{ errors.newPassword }}
            </div>
            <div class="password-requirements">
              <h4>密码要求：</h4>
              <ul>
                <li :class="{ 'met': passwordForm.newPassword.length >= 8 }">
                  <span class="requirement-icon">{{ passwordForm.newPassword.length >= 8 ? '✅' : '❌' }}</span>
                  至少8个字符
                </li>
                <li :class="{ 'met': hasUppercase }">
                  <span class="requirement-icon">{{ hasUppercase ? '✅' : '❌' }}</span>
                  包含大写字母
                </li>
                <li :class="{ 'met': hasLowercase }">
                  <span class="requirement-icon">{{ hasLowercase ? '✅' : '❌' }}</span>
                  包含小写字母
                </li>
                <li :class="{ 'met': hasNumber }">
                  <span class="requirement-icon">{{ hasNumber ? '✅' : '❌' }}</span>
                  包含数字
                </li>
                <li :class="{ 'met': hasSpecialChar }">
                  <span class="requirement-icon">{{ hasSpecialChar ? '✅' : '❌' }}</span>
                  包含特殊字符 (!@#$%^&*)
                </li>
              </ul>
            </div>
          </div>

          <div class="form-group">
            <label for="confirmPassword">
              <span class="label-text">确认新密码</span>
              <span class="required">*</span>
            </label>
            <div class="input-wrapper">
              <input 
                id="confirmPassword"
                v-model="passwordForm.confirmPassword" 
                :type="showConfirmPassword ? 'text' : 'password'"
                placeholder="请再次输入新密码"
                class="form-input"
                :class="{ 'error': errors.confirmPassword }"
                @input="validateConfirmPassword"
              />
              <button 
                type="button" 
                class="password-toggle"
                @click="showConfirmPassword = !showConfirmPassword"
              >
                {{ showConfirmPassword ? '👁️' : '🙈' }}
              </button>
            </div>
            <div v-if="errors.confirmPassword" class="error-message">
              {{ errors.confirmPassword }}
            </div>
          </div>

          <div class="form-actions">
            <button 
              class="btn btn-primary" 
              @click="submitChangePassword"
              :disabled="!canSubmit || submitting"
            >
              <span v-if="submitting" class="loading-spinner"></span>
              <span v-else class="btn-icon">🔐</span>
              {{ submitting ? '修改中...' : '确认修改' }}
            </button>
            <button class="btn btn-secondary" @click="resetForm">
              <span class="btn-icon">🔄</span>
              重置
            </button>
          </div>
        </div>
      </div>

      <!-- 安全提示卡片 -->
      <div class="security-tips-card">
        <h3>🔒 密码安全提示</h3>
        <div class="tips-content">
          <div class="tip-item">
            <div class="tip-icon">💡</div>
            <div class="tip-text">
              <strong>定期更换密码：</strong>
              建议每3-6个月更换一次密码，提高账户安全性
            </div>
          </div>
          <div class="tip-item">
            <div class="tip-icon">🚫</div>
            <div class="tip-text">
              <strong>避免使用常见密码：</strong>
              不要使用生日、手机号、123456等容易被猜到的密码
            </div>
          </div>
          <div class="tip-item">
            <div class="tip-icon">🔐</div>
            <div class="tip-text">
              <strong>使用强密码：</strong>
              包含大小写字母、数字和特殊字符的组合更安全
            </div>
          </div>
          <div class="tip-item">
            <div class="tip-icon">📱</div>
            <div class="tip-text">
              <strong>不要在公共场所输入：</strong>
              避免在网吧、图书馆等公共场所修改密码
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 成功提示模态框 -->
    <div v-if="showSuccessModal" class="modal-overlay" @click="showSuccessModal = false">
      <div class="modal-content success-modal" @click.stop>
        <div class="modal-header success-header">
          <div class="success-icon">🎉</div>
          <h3>密码修改成功</h3>
        </div>
        <div class="modal-body">
          <p>您的密码已经成功修改，请使用新密码重新登录。</p>
          <div class="success-actions">
            <button class="btn btn-primary" @click="handleLogout">
              <span class="btn-icon">🚪</span>
              重新登录
            </button>
            <button class="btn btn-secondary" @click="showSuccessModal = false">
              关闭
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { apiPut, getCurrentUser, apiGet } from '../../utils/api.js'

// 响应式数据
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const errors = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const showCurrentPassword = ref(false)
const showNewPassword = ref(false)
const showConfirmPassword = ref(false)
const submitting = ref(false)
const showSuccessModal = ref(false)

// 计算属性
const hasUppercase = computed(() => /[A-Z]/.test(passwordForm.newPassword))
const hasLowercase = computed(() => /[a-z]/.test(passwordForm.newPassword))
const hasNumber = computed(() => /\d/.test(passwordForm.newPassword))
const hasSpecialChar = computed(() => /[!@#$%^&*]/.test(passwordForm.newPassword))

const passwordStrength = computed(() => {
  const password = passwordForm.newPassword
  if (!password) return { class: '', text: '', percentage: 0 }
  
  let score = 0
  if (password.length >= 8) score += 20
  if (hasUppercase.value) score += 20
  if (hasLowercase.value) score += 20
  if (hasNumber.value) score += 20
  if (hasSpecialChar.value) score += 20
  
  if (score >= 80) return { class: 'strong', text: '强', percentage: 100 }
  if (score >= 60) return { class: 'medium', text: '中', percentage: 75 }
  if (score >= 40) return { class: 'weak', text: '弱', percentage: 50 }
  return { class: 'very-weak', text: '很弱', percentage: 25 }
})

const canSubmit = computed(() => {
  return passwordForm.currentPassword && 
         passwordForm.newPassword && 
         passwordForm.confirmPassword &&
         passwordForm.newPassword === passwordForm.confirmPassword &&
         passwordForm.newPassword.length >= 8 &&
         !Object.values(errors).some(error => error)
})

// 生命周期
onMounted(() => {
  // 页面加载完成后的初始化
})

// 方法
const validateNewPassword = () => {
  errors.newPassword = ''
  
  if (passwordForm.newPassword.length < 8) {
    errors.newPassword = '密码长度至少8位'
    return
  }
  
  if (!hasUppercase.value || !hasLowercase.value || !hasNumber.value || !hasSpecialChar.value) {
    errors.newPassword = '密码必须包含大小写字母、数字和特殊字符'
    return
  }
  
  if (passwordForm.newPassword === passwordForm.currentPassword) {
    errors.newPassword = '新密码不能与当前密码相同'
    return
  }
}

const validateConfirmPassword = () => {
  errors.confirmPassword = ''
  
  if (passwordForm.confirmPassword !== passwordForm.newPassword) {
    errors.confirmPassword = '两次输入的密码不一致'
  }
}

const clearError = (field) => {
  errors[field] = ''
}

const validateForm = () => {
  let isValid = true
  
  // 验证当前密码
  if (!passwordForm.currentPassword) {
    errors.currentPassword = '请输入当前密码'
    isValid = false
  }
  
  // 验证新密码
  validateNewPassword()
  if (errors.newPassword) {
    isValid = false
  }
  
  // 验证确认密码
  validateConfirmPassword()
  if (errors.confirmPassword) {
    isValid = false
  }
  
  return isValid
}

const submitChangePassword = async () => {
  if (!validateForm()) {
    return
  }
  
  submitting.value = true
  
  try {
    const currentUser = getCurrentUser()
    let targetUserId = currentUser?.id
    if (!targetUserId && currentUser?.username) {
      const profile = await apiGet(`/system/user/profile/by-username?username=${encodeURIComponent(currentUser.username)}`)
      targetUserId = profile?.id
      if (targetUserId) {
        localStorage.setItem('userId', String(targetUserId))
      }
    }
    if (!targetUserId) {
      throw new Error('未获取到当前用户ID，请重新登录')
    }
    const response = await apiPut(`/system/user/password/${targetUserId}`, {
      oldPassword: passwordForm.currentPassword,
      newPassword: passwordForm.newPassword
    })
    
    if (response && response.message) {
      showSuccessModal.value = true
      resetForm()
    }
  } catch (error) {
    console.error('修改密码失败:', error)
    
    // 处理特定错误
    if (error.message && error.message.includes('旧密码不正确')) {
      errors.currentPassword = '当前密码不正确'
    } else {
      alert('修改密码失败: ' + (error.message || '未知错误'))
    }
  } finally {
    submitting.value = false
  }
}

const resetForm = () => {
  Object.assign(passwordForm, {
    currentPassword: '',
    newPassword: '',
    confirmPassword: ''
  })
  
  Object.assign(errors, {
    currentPassword: '',
    newPassword: '',
    confirmPassword: ''
  })
  
  showCurrentPassword.value = false
  showNewPassword.value = false
  showConfirmPassword.value = false
}

const handleLogout = () => {
  // 这里应该调用登出接口，然后跳转到登录页
  // 暂时使用简单的页面刷新
  window.location.reload()
}
</script>

<style scoped>
.change-password {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  color: #2c3e50;
  font-size: 28px;
  font-weight: 600;
}

.breadcrumb {
  color: #7f8c8d;
  font-size: 14px;
}

.password-content {
  display: grid;
  gap: 24px;
  grid-template-columns: 2fr 1fr;
  max-width: 1200px;
}

.password-card, .security-tips-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 32px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e5e7eb;
}

.header-icon {
  font-size: 48px;
  width: 80px;
  height: 80px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.header-text h2 {
  margin: 0 0 8px 0;
  color: #2c3e50;
  font-size: 24px;
  font-weight: 600;
}

.header-text p {
  margin: 0;
  color: #7f8c8d;
  font-size: 16px;
}

.password-form {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group label {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-bottom: 8px;
  color: #374151;
  font-weight: 500;
  font-size: 14px;
}

.required {
  color: #ef4444;
  font-weight: bold;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.form-input {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.form-input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-input.error {
  border-color: #ef4444;
  box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.1);
}

.password-toggle {
  position: absolute;
  right: 12px;
  background: none;
  border: none;
  cursor: pointer;
  padding: 4px;
  font-size: 16px;
  color: #6b7280;
  transition: color 0.2s ease;
}

.password-toggle:hover {
  color: #374151;
}

.error-message {
  margin-top: 4px;
  color: #ef4444;
  font-size: 12px;
}

.password-strength {
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.strength-bar {
  flex: 1;
  height: 6px;
  background: #e5e7eb;
  border-radius: 3px;
  overflow: hidden;
}

.strength-fill {
  height: 100%;
  transition: all 0.3s ease;
}

.strength-fill.very-weak {
  background: #ef4444;
}

.strength-fill.weak {
  background: #f59e0b;
}

.strength-fill.medium {
  background: #f59e0b;
}

.strength-fill.strong {
  background: #10b981;
}

.strength-text {
  font-size: 12px;
  font-weight: 500;
  min-width: 40px;
}

.strength-text.very-weak {
  color: #ef4444;
}

.strength-text.weak {
  color: #f59e0b;
}

.strength-text.medium {
  color: #f59e0b;
}

.strength-text.strong {
  color: #10b981;
}

.password-requirements {
  margin-top: 16px;
  padding: 16px;
  background: #f9fafb;
  border-radius: 8px;
  border: 1px solid #e5e7eb;
}

.password-requirements h4 {
  margin: 0 0 12px 0;
  color: #374151;
  font-size: 14px;
  font-weight: 600;
}

.password-requirements ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

.password-requirements li {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  color: #6b7280;
  font-size: 13px;
}

.password-requirements li:last-child {
  margin-bottom: 0;
}

.password-requirements li.met {
  color: #10b981;
}

.requirement-icon {
  font-size: 14px;
}

.form-actions {
  display: flex;
  gap: 16px;
  margin-top: 8px;
}

/* 按钮样式 */
.btn {
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  min-width: 120px;
  justify-content: center;
}

.btn-primary {
  background: #667eea;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background: #5a67d8;
}

.btn-secondary {
  background: #6b7280;
  color: white;
}

.btn-secondary:hover {
  background: #4b5563;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-icon {
  font-size: 16px;
}

.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid #ffffff;
  border-top: 2px solid transparent;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 安全提示卡片 */
.security-tips-card h3 {
  margin: 0 0 20px 0;
  color: #2c3e50;
  font-size: 18px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.tips-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.tip-item {
  display: flex;
  gap: 12px;
  padding: 16px;
  background: #f8fafc;
  border-radius: 8px;
  border-left: 4px solid #667eea;
}

.tip-icon {
  font-size: 20px;
  flex-shrink: 0;
}

.tip-text {
  color: #374151;
  font-size: 14px;
  line-height: 1.5;
}

.tip-text strong {
  color: #2c3e50;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 12px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  max-width: 500px;
  width: 90%;
}

.success-modal .modal-header {
  padding: 24px;
  text-align: center;
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  color: white;
  border-radius: 12px 12px 0 0;
}

.success-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.success-modal .modal-header h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.modal-body {
  padding: 24px;
  text-align: center;
}

.modal-body p {
  margin: 0 0 24px 0;
  color: #374151;
  font-size: 16px;
  line-height: 1.5;
}

.success-actions {
  display: flex;
  gap: 16px;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .password-content {
    grid-template-columns: 1fr;
  }
  
  .card-header {
    flex-direction: column;
    text-align: center;
  }
  
  .form-actions {
    flex-direction: column;
  }
  
  .success-actions {
    flex-direction: column;
  }
}
</style>
